package com.neteast.androidclient.contact.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.neteast.androidclient.contact.Constant;
import com.neteast.androidclient.contact.R;
import com.neteast.androidclient.contact.adapter.ContactPageAdapter;
import com.neteast.androidclient.contact.adapter.SimpleStrAdapter;
import com.neteast.androidclient.contact.adapter.SingleScreenAdapter;
import com.neteast.androidclient.contact.domain.Contact;
import com.neteast.androidclient.contact.util.ContactsUtils;
import com.neteast.androidclient.contact.util.LetterTouchListener;
import com.neteast.androidclient.contact.util.LoginUtil;
import com.neteast.androidclient.contact.util.NetUtil;
import com.neteast.androidclient.contact.util.PinYinUtil;
import com.neteast.androidclient.contact.widget.GroupPanel;
import com.neteast.androidclient.contact.widget.LetterListView;

/**
 * 显示所有联系人信息的页面
 * 
 * @author yangxun 2012-3-13 下午1:33:04
 */
public class ContactActivity extends Activity implements OnClickListener {
	private String TAG = "ContactActivity";
	private Context mContext;
	private LayoutInflater mInflater;
	private WindowManager wManager; 
	private int WINDOW_HEIGHT ; 
	/** handler标志.删除单个云好友.  */
	public static final int DELETE_CLOUD_ITEM = 1;
	/** handler标志.删除单个通讯好友.  */
	public static final int DELETE_COMM_ITEM = 2;
	/** handler标志.从本地通讯录导入完成.  */
	public static final int IMPORT_CONTACT_FINISH = 3;
	/** handler标志.获取好友完成.  */
	public static final int LOAD_FRIENDS_FINISH = 4;
	/** handler标志.获取好友分组完成.  */
	public static final int LOAD_GROUP_FINISH = 5;
	/** handler标志.错误信息提示.  */
	public static final int ERROR = 6;
	/** handler标志.暂无云好友.  */
	public static final int HAVE_NO_CLOUD_FRIENDS = 7;
	/** handler标志.暂无通讯好友.  */
	public static final int HAVE_NO_COMM_FRIENDS = 8;
	/** handler标志.获取单个云好友信息.  */
	public static final int GET_CLOUD_DETAIL_FINISH = 9;
	/** handler标志.获取单个通讯好友信息.  */
	public static final int GET_CONTACT_DETAIL_FINISH = 10;
	/** handler标志.增加分组.  */
	public static final int ADD_GROUP = 11;
	/** handler标志.删除分组.  */
	public static final int DELETE_GROUP = 12;
	/** handler标志.重命名分组.  */
	public static final int MODIFY_GROUP = 13;
	/** handler标志.搜索完成.  */
	public static final int  SEARCH_FINISH= 14;
	
	
	/** 云好友是否在管理模式. */
	private int currentCloudDelMode = 0;
	/** 通讯好友是否在管理模式. */
	private int currentCommDelMode = 0;
	/** 管理联系人. */
	private final int IS_DELETE_MODE = 1;
	/** 退出管理模式. */
	private final int NOT_DELETE_MODE = 0;
	
	/** 新建联系人返回结果. */
	private final int createNewRequestCode = 1;
	/** 修改云好友返回结果. */
	private final int modifyCloudRequestCode = 2;
	/** 修改通讯好友返回结果. */
	private final int modifyContactRequestCode = 3;
	/** 云好友和通讯录好友切换标签按钮. */
	private Button tab1, tab2;
	/** 右上角下拉菜单按钮. */
	private ImageView btnMore;
	/** 右上角下拉菜单弹出窗口. */
	private PopupWindow morePopupWindow;
	/** 右上角下拉菜单弹出窗口视图. */
	private LinearLayout morePopupView;
	/** 组操作弹窗视图. */
	private View groupPopupView;
	/** 组操作菜单弹出窗口. */
	private PopupWindow groupPopupWindow;
	/** 分组列表的linearLayout. */
	private GroupPanel groupPanel;
	/** 分组列表. */
	private ListView groupListView;
	/** 云好友分组数据.  */
	private ArrayList<String> cloudGroupList;
	/** 通讯好友分组数据.  */
	private ArrayList<String> contactGroupList;
	/** 判断当前在哪个标签页上，1是云好友，2是通讯好友. */ 
	private int currentView; 
	/** 对话框显示. */
	private Dialog progressDialog;
	/** 字母索引列表. */
	private LetterListView searchInexList;
	/** 字母索引数据. */
	private ArrayList<String> searchIndexs;
	/** 搜索输入框. */
	private EditText searchEdit;
	/** 云好友页面视图列表. */
	private List<View> cloudListViews;
	/** 通讯好友页面视图列表列表. */
	private List<View> contactListViews;
	/** 每页显示的数量，Adapter保持一致. */
	public static final float PAGE_SIZE = 12.0f;
	/** 云好友ViewPager适配器. */
	private ContactPageAdapter cloudPageAdapter;
	/** 通讯好友ViewPager适配器. */
	private ContactPageAdapter contactPageAdapter;
	/** 联系人ViewPager视图. */
	private ViewPager mViewPager;
	/** 分组列表适配器. */
	private SimpleStrAdapter groupAdapter;
	/** 云好友列表. */
	private ArrayList<Contact> cloudList;
	/** 通讯好友列表. */
	private ArrayList<Contact> contactList;
	/** 当前列表，当切换分组时该列表不等于云好友或者通讯好友列表 */
	private ArrayList<Contact> currentList;
	/** 删除分组对话框高度. */
	public static final int DLG_DELETE_GROUP_HEIGHT = 178;
	/** 删除分组对话框宽度. */
	public static final int DLG_DELETE_GROUP_WIDTH = 376;
	/** 重命名分组对话框高度. */
	public static final int DLG_EDIT_GROUP_HEIGHT = 248;
	/** 重命名分组对话框宽度. */
	public static final int DLG_EDIT_GROUP_WIDTH = 504;
	/** 导入联系人线程. */
	private Thread importThread;
	/** 获取云好友数据线程. */
	private Thread loadCloudThread;
	/** 获取通讯好友数据线程. */
	private Thread loadContactThread;
	/** 获取联系人详细信息线程. */
	private Thread loadDetailInfoThread;
	/**
	 * GridView的监听事件
	 */
	public OnItemClickListener gridListener = new OnItemClickListener() {

		public void onItemClick(AdapterView<?> parent, View view,
				final int position, long id) {
			showProgressDialog(mContext, progressDialog, "正在获取个人信息，请稍候");

			loadDetailInfoThread = new Thread(new Runnable() {

				public void run() {
					try {
						if (isCloud()) {
							int listPosition = (mViewPager.getCurrentItem() * 12) + position;
							Contact detailInfo = NetUtil.getContactFromServer(
									mContext,
									currentList.get(listPosition).contactId);
							Message msg = new Message();
							msg.what = GET_CLOUD_DETAIL_FINISH;
							msg.obj = detailInfo;
							msg.arg1 = listPosition;
							handler.sendMessage(msg);

						} else {
							int listPosition = (mViewPager.getCurrentItem() * 12) + position;
							Contact detailInfo = NetUtil.getContactFromServer(
									mContext,
									currentList.get(listPosition).contactId);
							Message msg = new Message();
							msg.what = GET_CONTACT_DETAIL_FINISH;
							msg.obj = detailInfo;
							msg.arg1 = listPosition;
							handler.sendMessage(msg);
						}
					} catch (Exception e) {
						Message msg = new Message();
						msg.what = ERROR;
						msg.obj = "获取联系人信息网络错误,请重试";
						msg.arg1 = 0;
						handler.sendMessage(msg);
						e.printStackTrace();
					}
				}
			});
			loadDetailInfoThread.start();

		}
	};
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DELETE_CLOUD_ITEM: {//arg1是子view在gridView中的位置，arg2是当前页数
				int position = msg.arg1;
				int page = msg.arg2;
				cloudList.remove((page * (int)PAGE_SIZE) + position);
				loadCloudView(cloudList);
				mViewPager.setCurrentItem(page, false);
				progressDialog.dismiss();
			}
				break;
			case DELETE_COMM_ITEM: {
				int position = msg.arg1;
				int page = msg.arg2;
				contactList.remove((page * (int)PAGE_SIZE) + position);
				loadContactView(contactList);
				mViewPager.setCurrentItem(page, false);
				progressDialog.dismiss();
			}
				break;
			case IMPORT_CONTACT_FINISH:
				progressDialog.dismiss();
				loadContactView(contactList);
				Toast.makeText(mContext, "导入成功", Toast.LENGTH_SHORT).show();
				break;
			case LOAD_FRIENDS_FINISH:
				if(isCloud()){
					loadCloudView(cloudList);
				}else{
					loadContactView(contactList);
				}
				progressDialog.dismiss();
				break;
			case LOAD_GROUP_FINISH:
				if(isCloud()){
					if(cloudGroupList.size() != 0){
						loadGroupList(cloudGroupList);
					}
				}else{
					if(contactGroupList.size() != 0){
						loadGroupList(contactGroupList);
					}
				}
				break;
			case ERROR:
				String errorMsg = (String) msg.obj;
				int progressDismiss = msg.arg1;//为0时消失进度对话框，为1时不消失
				if(progressDismiss == 0){
					if(progressDialog.isShowing()){
						progressDialog.dismiss();
					}
				}
				Toast.makeText(mContext, errorMsg, Toast.LENGTH_SHORT).show();
				break;
			case HAVE_NO_CLOUD_FRIENDS:
				if(progressDialog.isShowing()){
					progressDialog.dismiss();
				}
				Toast.makeText(mContext, "暂无云好友", Toast.LENGTH_SHORT).show();
				break;
			case HAVE_NO_COMM_FRIENDS:
				if(progressDialog.isShowing()){
					progressDialog.dismiss();
				}
				Toast.makeText(mContext, "暂无通讯好友，请从本地导入", Toast.LENGTH_SHORT).show();
				break;
			case GET_CLOUD_DETAIL_FINISH:
				progressDialog.dismiss();
					Contact cloudInfo = (Contact) msg.obj;
					if (cloudInfo != null) {
						startActivityForResult(
								new Intent(mContext, NewContactActivity.class)
										.putExtra("contactInfo", cloudInfo)
										.putExtra("position", msg.arg1),
								modifyCloudRequestCode);
					}
				break;
			case GET_CONTACT_DETAIL_FINISH:
				progressDialog.dismiss();
					Contact contactInfo = (Contact) msg.obj;
					if (contactInfo != null) {
						startActivityForResult(
								new Intent(mContext, NewContactActivity.class)
										.putExtra("contactInfo", contactInfo)
										.putExtra("position", msg.arg1),
										modifyContactRequestCode);
					}
				break;
			case ADD_GROUP:
				String newGroup = String.valueOf(msg.obj);
				ArrayList<String> tmp ;
				if(isCloud()){
					MainActivity.cloudGroups.add(newGroup);
//					tmp = (ArrayList<String>) cloudGroupList.clone();
					cloudGroupList.add(newGroup);
					tmp = PinYinUtil.sortName(MainActivity.cloudGroups);
				}else{
					MainActivity.contactGroups.add(newGroup);
					contactGroupList.add(newGroup);
//					tmp = (ArrayList<String>) contactGroupList.clone();
					tmp = PinYinUtil.sortName(MainActivity.contactGroups);
				}
				
				int i = 0;
				for(String str : tmp){
					if(str.equals(newGroup)){
						break;
					}
					i++;
				}
				groupAdapter.addView(i,newGroup);
				progressDialog.dismiss();
				break;
			case DELETE_GROUP:
				SimpleStrAdapter adapter = (SimpleStrAdapter) msg.obj;
				int delPosition = msg.arg1;
				adapter.removeView(delPosition);
				if(isCloud()){
					MainActivity.cloudGroups.remove(delPosition);
					cloudGroupList.remove(delPosition);
				}else{
					MainActivity.contactGroups.remove(delPosition);
					contactGroupList.remove(delPosition);
				}
				progressDialog.dismiss();
				break;
			case MODIFY_GROUP:
				int modPosition = msg.arg1;
				String newName = String.valueOf(msg.obj);
				groupAdapter.relaceName(modPosition, newName);
				if(isCloud()){
					MainActivity.cloudGroups.set(modPosition, newName);
					cloudGroupList.set(modPosition, newName);
				}else{
					MainActivity.contactGroups.set(modPosition, newName);
					contactGroupList.set(modPosition, newName);
				}
				progressDialog.dismiss();
				break;
			case SEARCH_FINISH:
				final ArrayList<Contact> result = (ArrayList<Contact>) msg.obj;
				if(isCloud()){
					mViewPager.removeAllViews();
					loadCloudView(result);
				}else{
					mViewPager.removeAllViews();
					loadContactView(result);
				}
//				progressDialog.dismiss();
				break;
			}
			super.handleMessage(msg);
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contact);
		wManager = getWindowManager();
		WINDOW_HEIGHT = wManager.getDefaultDisplay().getHeight();
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		findView();
		init();
		showProgressDialog(mContext, progressDialog, "正在获取好友列表，请稍候");
	}

	@Override
	protected void onPause() {
		if(morePopupWindow.isShowing()){
			morePopupWindow.dismiss();
		}
		if(groupPopupWindow.isShowing()){
			groupPopupWindow.dismiss();
		}
		super.onPause();
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	public void onClick(View v) {
		
		switch (v.getId()) {
		case R.id.Tab1:
			switchView(1);
			mViewPager.removeAllViews();
			if (! ContactsUtils.validateIsNotNull(cloudList)) {
				showProgressDialog(mContext, progressDialog, "正在获取云好友列表，请稍候");
				getDataFromInternet(0);
			} else {
				if(cloudPageAdapter != null){
					mViewPager.setAdapter(cloudPageAdapter);
					setCurrentList(cloudList);
				}else{
					loadCloudView(cloudList);
				}
			}
			break;
		case R.id.Tab2:
			switchView(2);
			mViewPager.removeAllViews();
			if (! ContactsUtils.validateIsNotNull(contactList)) {
				showProgressDialog(mContext, progressDialog, "正在获取通讯好友列表，请稍候");
				getDataFromInternet(1);
			} else{
				if(contactPageAdapter != null){
					mViewPager.setAdapter(contactPageAdapter);
					setCurrentList(contactList);
				}else{
					loadContactView(contactList);
				}
			}
			break;
		case R.id.btnMore:
			showPopupWindow(currentView);
			break;
		case R.id.btnCreateNew:
			startActivityForResult(new Intent(ContactActivity.this,
					ContactEditActivity.class).putExtra("isNew", true), createNewRequestCode);
			morePopupWindow.dismiss();
			break;
		case R.id.btnImport:
			showImportDialog();
			morePopupWindow.dismiss();
			break;
		case R.id.btnFindFriends:
			break;
		
		case R.id.btnCloudManage:
			if(ContactsUtils.validateIsNotNull(cloudList)){
				manageContact(cloudPageAdapter);
			}
			
			break;
		case R.id.btnContactManage:
			if(ContactsUtils.validateIsNotNull(contactList)){
				manageContact(contactPageAdapter);
			}
			break;
		}
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		int action = ev.getAction();
		switch (action) {
		case MotionEvent.ACTION_DOWN:
			if (morePopupWindow.isShowing()) {
				morePopupWindow.dismiss();
				return false;
			}
			if (groupPopupWindow.isShowing()) {
				groupPopupWindow.dismiss();
				return false;
			}
			
			break;
		}

		return super.dispatchTouchEvent(ev);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if(groupPanel.isOpen()){
			groupPanel.setOpen(false, true);
			return true;
		}
		return super.onTouchEvent(event);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(data == null ){
			return;
		}
		if(requestCode == createNewRequestCode && resultCode == Activity.RESULT_OK){//新建联系人
			if(Constant.DEBUG){
				Log.d(TAG, "contactPageAdapter count before : "+contactPageAdapter.getCount());
			}
			
			Contact contact = (Contact) data.getSerializableExtra("contact");
			if(contactList == null){
				contactList = new ArrayList<Contact>();
			}
			addContact(contactList, contact, mContext);
			MainActivity.contactFriends.add(contact);
			if(Constant.DEBUG){
				Log.d(TAG, "contactPageAdapter count after : "+contactPageAdapter.getCount());
			}
			
		}else if(requestCode == modifyCloudRequestCode && resultCode == Activity.RESULT_OK){//修改云好友信息
			Contact contact = (Contact) data.getSerializableExtra("contact");
			if(currentCloudDelMode == IS_DELETE_MODE){
				contact.isDelete = true;
			}
			int position = data.getIntExtra("position", -1);
			SingleScreenAdapter dateAdapter = (SingleScreenAdapter)((GridView)cloudPageAdapter.getItem(mViewPager.getCurrentItem())).getAdapter();
			dateAdapter.modifyItem(position - (mViewPager.getCurrentItem() * 12), contact);
			currentList.set(position, contact);
			int modifyContactId = currentList.get(position).contactId;
			for(int i = 0; i<cloudList.size(); i++){
				if(cloudList.get(i).contactId == modifyContactId){
					cloudList.set(i, contact);
				}
			}
			if(Constant.DEBUG){
				Log.d(TAG, "position in all : "+position +" position in currentView : "+ (position - (mViewPager.getCurrentItem() * 12)));
			}
			
		}else if(requestCode == modifyContactRequestCode && resultCode == Activity.RESULT_OK){//修改通讯好友信息
			Contact contact = (Contact) data.getSerializableExtra("contact");
			if(currentCommDelMode == IS_DELETE_MODE){
				contact.isDelete = true;
			}
			int position = data.getIntExtra("position", -1);
			SingleScreenAdapter dateAdapter = (SingleScreenAdapter)((GridView)contactPageAdapter.getItem(mViewPager.getCurrentItem())).getAdapter();
			dateAdapter.modifyItem(position - (mViewPager.getCurrentItem() * 12), contact);
			currentList.set(position, contact);
			int modifyContactId = currentList.get(position).contactId;
			for(int i = 0; i<contactList.size(); i++){
				if(contactList.get(i).contactId == modifyContactId){
					contactList.set(i, contact);
				}
			}
			if(Constant.DEBUG){
				Log.d(TAG, "position in all : "+position +" position in currentView : "+ (position - (mViewPager.getCurrentItem() * 12)));
			}
			
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	private void findView() {
		tab1 = (Button) findViewById(R.id.Tab1);
		tab2 = (Button) findViewById(R.id.Tab2);
		btnMore = (ImageView) findViewById(R.id.btnMore);
		tab1.setOnClickListener(this);
		tab2.setOnClickListener(this);
		btnMore.setOnClickListener(this);
		groupListView = (ListView) findViewById(R.id.groupList);
		searchInexList = (LetterListView)findViewById(R.id.searchIndex);
		searchEdit = (EditText) findViewById(R.id.search_edit);
		mViewPager = (ViewPager) findViewById(R.id.viewPager);
        groupPanel = (GroupPanel) findViewById(R.id.leftPanel);  
        groupPanel.setClickable(true);
        android.view.ViewGroup.LayoutParams lp;        
        lp=groupPanel.getLayoutParams();
        lp.height=WINDOW_HEIGHT;
        groupPanel.setLayoutParams(lp);
        groupPanel.setOnPanelListener(new GroupPanel.OnPanelListener() {
			
			public void onPanelOpened(GroupPanel panel) {
				
			}
			
			public void onPanelClosed(GroupPanel panel) {
				// TODO Auto-generated method stub
				
			}
		});
	}

	private void init() {
		mContext = ContactActivity.this;
		cloudListViews = new ArrayList<View>();
		contactListViews = new ArrayList<View>();
		currentList = new ArrayList<Contact>();
		
		mInflater = LayoutInflater.from(mContext);
		progressDialog = new Dialog(mContext, R.style.progressDialogStyle);
		cloudList = new ArrayList<Contact>();
		contactList = new ArrayList<Contact>();
		
		// 创建弹窗对象
		morePopupView = (LinearLayout) getLayoutInflater().inflate(
				R.layout.popup_view, null);
		morePopupWindow = new PopupWindow(morePopupView,
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false);
		groupPopupView = mInflater.inflate(R.layout.group_manager_view, null);
		groupPopupWindow = new PopupWindow(groupPopupView,
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false);
		searchIndexs = new ArrayList<String>();
		String[] tmp = getResources().getStringArray(
				R.array.search_index_arrays);
		for (int i = 0; i < tmp.length; i++) {
			searchIndexs.add(tmp[i]);
		}
		cloudGroupList = new ArrayList<String>();
		contactGroupList = new ArrayList<String>();
		switchView(2);
		getDataFromInternet(1);
		searchEdit.addTextChangedListener(new TextWatcher() {

			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				doSearch();
					
			}
		});
		searchEdit.setLongClickable(false);
		
		//解决输入框长按报错问题
		searchEdit.setOnLongClickListener(new OnLongClickListener() {
			
			public boolean onLongClick(View v) {
				return true;
			}
		});
		
	}

	/**
	 * 根据选择的按钮变换背景
	 * @param tab 当前屏幕 为1时为云好友，为2时为通讯好友
	 * */
	private void switchView(int tab) {
		for (int i = 0; i < groupListView.getChildCount(); i++) {
			if (i == 0) {
				groupListView.getChildAt(i).setBackgroundDrawable(
						mContext.getResources().getDrawable(
								R.drawable.group_list_item_selector));
			}
		}
		searchInexList.refresh();
		searchEdit.setText("");
		if (tab == 1) {
			initSearchIndex(tab);
			tab1.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.tab_friends_selected));
			tab2.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.tab_friends_normal));
			tab1.setTextColor(mContext.getResources().getColor(
					R.color.tab_text_blue));
			tab2.setTextColor(Color.WHITE);
			loadGroupList(cloudGroupList);
		} else if (tab == 2) {
			initSearchIndex(tab);
			tab2.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.tab_friends_selected));
			tab1.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.tab_friends_normal));
			tab1.setTextColor(Color.WHITE);
			tab2.setTextColor(mContext.getResources().getColor(
					R.color.tab_text_blue));
			loadGroupList(contactGroupList);

		}

	}

	/**
	 * 从网络获取数据
	 * 根据传入类型判断获取数据类型
	 * @param type 为0时获取云好友数据，为1时获取通讯好友数据
	 * */
	private void getDataFromInternet(int type) {
		switch(type){
		case 0:{
			loadCloudThread = new Thread(new Runnable() {

				public void run() {
					try {
						NetUtil.getCloudFriends(mContext,
								LoginUtil.getLastLoginUserId(mContext));
					} catch (Exception e) {
						setCurrentList(MainActivity.cloudFriends);
						handler.obtainMessage(ERROR, 0, 0, e.getMessage()).sendToTarget();
						e.printStackTrace();
					}
					if (ContactsUtils.validateIsNotNull(MainActivity.cloudFriends)) {
						cloudList.addAll(MainActivity.cloudFriends);
						handler.sendEmptyMessage(LOAD_FRIENDS_FINISH);
					}
					
					try {
						NetUtil.getCloudGroups(mContext, LoginUtil.getLastLoginUserId(mContext));
						if(cloudGroupList.size() == 0){
							cloudGroupList.addAll(PinYinUtil.sortName(MainActivity.cloudGroups));
						}
						handler.sendEmptyMessage(LOAD_GROUP_FINISH);
					} catch (Exception e) {
						handler.obtainMessage(ERROR, 0, 0, e.getMessage()).sendToTarget();
						e.printStackTrace();
					}
				}
			});	
			loadCloudThread.start();
		}
			break;
		case 1:
			loadContactThread = new Thread(new Runnable() {
				
				public void run() {
					try {
						ArrayList<Contact> result = NetUtil.getContactFriends(mContext, LoginUtil.getLastLoginUserId(mContext));
						if(ContactsUtils.validateIsNotNull(result)){
							contactList.addAll(result);
							handler.sendEmptyMessage(LOAD_FRIENDS_FINISH);
						}else{
							handler.sendEmptyMessage(HAVE_NO_COMM_FRIENDS);
						}
					} catch (Exception e) {
						setCurrentList(MainActivity.contactFriends);
						handler.obtainMessage(ERROR, 0, 0, e.getMessage()).sendToTarget();
						e.printStackTrace();
					}
					try {
						NetUtil.getContactGroups(mContext, LoginUtil.getLastLoginUserId(mContext));
						if(contactGroupList.size() == 0){
							contactGroupList.addAll(PinYinUtil.sortName(MainActivity.contactGroups));
						}
						handler.sendEmptyMessage(LOAD_GROUP_FINISH);
					} catch (Exception e) {
						handler.obtainMessage(ERROR, 0, 0, e.getMessage()).sendToTarget();
						e.printStackTrace();
					}
				}
			});
			loadContactThread.start();
			
			break;
		}
		
	}
	
	/**
	 * 重载整个视图
	 * @param isReLoad 判断是否是重载
	 * @param position 点击的view位置
	 * @param list 列表数据来源
	 * */
	private void loadCloudView(final ArrayList<Contact> list){
		cloudListViews = setGrid(list);
		cloudPageAdapter = new ContactPageAdapter(cloudListViews); 
		mViewPager.setAdapter(cloudPageAdapter);
		setCurrentList(list);
	}

	/**
	 * 载入通讯录画面 
	 * @param isReLoad 判断是否是重载
	 * @param position 点击的view位置
	 * @param list 列表数据来源
	 * */
	private void loadContactView(final ArrayList<Contact> list){
		contactListViews = setGrid(list);
		contactPageAdapter = new ContactPageAdapter(contactListViews);
		mViewPager.setAdapter(contactPageAdapter);
		setCurrentList(list);
	}

	/**
	 * 初始化快速索引列表
	 * @param tab 当前屏幕 为1时为云好友，为2时为通讯好友
	 * */
	private void initSearchIndex(int tab) {
		currentView = tab;
		
			searchInexList.setOnTouchingLetterChangedListener(new LetterTouchListener() {
				
				public void filterByLitter(String letter) {
					if(ContactsUtils.validateIsNotNull(currentList)){
						int index = 0;
							for(Contact contact : currentList){
								if(letter.equals(String.valueOf(contact.sortKey))){
									break;
								}
								index++;
							}
						if(index >= currentList.size()){
							//TODO 未找到
							if(Constant.DEBUG){
								Log.d(TAG, "no Result!!! "+index);
							}
						}else{
							mViewPager.setCurrentItem(Math.round(index/12), false);
							if(Constant.DEBUG){
								Log.d(TAG, "move!!! ---------------"+index);
							}
						}
					}
				}
			});
//		
//		if (isCloud()) {
//			btnSearch.setOnClickListener(new OnClickListener() {
//
//				public void onClick(View v) {
//					startActivity(new Intent(mContext, SearchActivity.class).putExtra("isCloud", true));
//				}
//			});
//		} else {
//			btnSearch.setOnClickListener(new OnClickListener() {
//
//				public void onClick(View v) {
//					startActivity(new Intent(mContext, SearchActivity.class).putExtra("isCloud", false));
//				}
//			});
//		}
	}

	/**
	 * 设置分组列表视图
	 * @param array 分组列表
	 * */
	private void loadGroupList(final ArrayList<String> groupList) {
		final ArrayList<String> array = PinYinUtil.sortName(groupList);
		groupAdapter = new SimpleStrAdapter(
				mContext, array, R.layout.group_list_item);
		final View dialogView = mInflater.inflate(R.layout.dlg_add_group, null);
		final Dialog dialog = new Dialog(mContext, R.style.DialogStyle);
		final EditText nameInput = (EditText)dialogView.findViewById(R.id.messageEdit);
		// 弹出框内的组件
		final Button btnOk = (Button) dialogView.findViewById(R.id.btnOk);
		final Button btnCancel = (Button) dialogView
				.findViewById(R.id.btnCancel);

		LinearLayout footerview = (LinearLayout) getLayoutInflater().inflate(
				R.layout.add_group, null);
		LinearLayout headerView = (LinearLayout) getLayoutInflater().inflate(
				R.layout.group_list_item, null);
		headerView.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.group_list_item_selector));
		if (groupListView.getFooterViewsCount() <= 0) {
			groupListView.addFooterView(footerview);
		}
		if (groupListView.getHeaderViewsCount() <= 0) {
			((TextView) headerView.findViewById(R.id.text)).setText("全部");
			groupListView.addHeaderView(headerView);
		}
		groupListView.setAdapter(groupAdapter);

		groupListView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				//新建组
				
				Log.d(TAG, "--------------position--"+ position+"-----------"+parent.getChildCount());
				if(position != parent.getChildCount()-1){
					for(int i = 0; i<parent.getChildCount();i++){
						if(i != position){
							parent.getChildAt(i).setBackgroundResource(R.color.transparent);
						}
					}
					view.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.group_list_item_selector));
				
				}
				
				if (position == groupAdapter.getCount() + 1) {
					dialog.setContentView(dialogView);
					dialog.show();
				}else if(position == 0){//选择全部
					searchInexList.refresh();
					if(currentView == 1 && ContactsUtils.validateIsNotNull(cloudList)){
						loadCloudView(cloudList);
					}else if(currentView == 2 && ContactsUtils.validateIsNotNull(contactList)){
						loadContactView(contactList);
					}
				}else{
					searchInexList.refresh();
					if(isCloud()){
						ArrayList<Contact> tmpList = new ArrayList<Contact>();
						for(Contact contact : cloudList){
							if(contact.groups != null ){
								String[] group = (contact.groups).split(",");
								for(int i = 0; i<group.length; i++){
									if(group[i].equals(groupAdapter.getItem(position - 1))){
										if(!tmpList.contains(contact)){
											tmpList.add(contact);
										}
									}
								}
							}
						}
						if(tmpList != null && tmpList.size() != 0){
							loadCloudView(tmpList);
						}else{
							Toast.makeText(mContext, "该分组内暂无好友", Toast.LENGTH_SHORT).show();
							mViewPager.removeAllViews();
							loadCloudView(new ArrayList<Contact>());
						}
					}else {
						ArrayList<Contact> tmpList = new ArrayList<Contact>();
						for(Contact contact : contactList){
							if(contact.groups != null ){
								String[] group = (contact.groups).split(",");
								for(int i = 0; i<group.length; i++){
									if(group[i].equals(groupAdapter.getItem(position - 1))){
										if(!tmpList.contains(contact)){
											tmpList.add(contact);
										}
									}
								}
							}
						}
						if(tmpList != null && tmpList.size() != 0){
							loadContactView(tmpList);
						}else{
							Toast.makeText(mContext, "该分组内暂无好友", Toast.LENGTH_SHORT).show();
							mViewPager.removeAllViews();
							loadContactView(new ArrayList<Contact>());
						}
					}
				}
			}
		});
		groupListView.setOnItemLongClickListener(new OnItemLongClickListener() {

			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (position == groupAdapter.getCount() + 1) {
					
				} else if (position == 0) {
//					if (groupPopupWindow.isShowing()) {
//						groupPopupWindow.dismiss();
//					}
//					groupPopupWindow.showAtLocation(parent, Gravity.LEFT, 180, 0);
//					setGroupManger(groupPopupView, groupAdapter, position - 1);
				} else {
					if (groupPopupWindow.isShowing()) {
						groupPopupWindow.dismiss();
					}
					groupPopupWindow.showAtLocation(parent, Gravity.LEFT, 180, 0);
					setGroupManger(groupPopupView, groupAdapter, position - 1);
				}
				return true;
			}
		});
		// 新建分组对话框中的按键监听
		btnOk.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				final String groupName = (nameInput.getText().toString().trim()).equals("") 
						? ContactsUtils.getCurrentData() : nameInput.getText().toString().trim();
//				if (groupName != null && !groupName.equals("")) {
					for(String str : array){
						if(groupName.equals(str)){
							Toast.makeText(mContext, "分组名称不能重复", Toast.LENGTH_SHORT).show();
							return;
						}
					}
					showProgressDialog(mContext, progressDialog, "正在添加分组...");
					if(isCloud()){
						new Thread(new Runnable() {
							public void run() {
								try {
									NetUtil.addCloudGroup(mContext, groupName);
									handler.obtainMessage(ADD_GROUP, groupName).sendToTarget();
								} catch (Exception e) {
									handler.obtainMessage(ERROR, 0, 0, "新增分组失败").sendToTarget();
									e.printStackTrace();
								}
							}
						}).start();
					}else {
						new Thread(new Runnable() {
							public void run() {
								try {
									NetUtil.addContactGroup(mContext, groupName);
									handler.obtainMessage(ADD_GROUP, groupName).sendToTarget();
								} catch (Exception e) {
									handler.obtainMessage(ERROR, 0, 0, "新增分组失败").sendToTarget();
									e.printStackTrace();
								}
							}
						}).start();
					}
					
					dialog.dismiss();
//				} else {
//					Toast.makeText(mContext, "请输入分组名称", Toast.LENGTH_LONG)
//							.show();
//				}
					nameInput.setText("");
			}
		});
		btnCancel.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				dialog.dismiss();

			}
		});

	}

	/**
	 * 设置分组管理按钮， 长按分组时调用
	 * @param popupView 弹出框视图
	 * @param adapter 分组列表适配器
	 * @param position 长按的分组序号
	 * */
	private void setGroupManger(View popupView, final SimpleStrAdapter adapter,
			final int position) {
		Button btnDelete = (Button) popupView.findViewById(R.id.btnDelete);
		Button btnReName = (Button) popupView.findViewById(R.id.btnReName);

		// 删除分组
		btnDelete.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				groupPopupWindow.dismiss();
				final View dialogView = mInflater.inflate(
						R.layout.dlg_add_group, null);
				final EditText messageEdit = ((EditText) dialogView
						.findViewById(R.id.messageEdit));
				final TextView messageText = ((TextView) dialogView
						.findViewById(R.id.messageText));
				final TextView titleText = ((TextView) dialogView
						.findViewById(R.id.titleText));
				messageEdit.setVisibility(View.GONE);
				messageText.setText(getString(R.string.delete_group_msg,
						adapter.getItem(position)));
				titleText.setText(getString(R.string.delete_group_title));
				final Dialog deleteDialog = new Dialog(mContext,
						R.style.DialogStyle);
				deleteDialog.setContentView(dialogView);
				deleteDialog.show();
				WindowManager.LayoutParams params = deleteDialog.getWindow()
						.getAttributes();
				params.width = LayoutParams.WRAP_CONTENT;
				params.height = LayoutParams.WRAP_CONTENT;
				deleteDialog.getWindow().setAttributes(params);
				((Button) dialogView.findViewById(R.id.btnOk))
						.setOnClickListener(new OnClickListener() {

							public void onClick(View v) {
								showProgressDialog(mContext, progressDialog, "正在删除分组");
								if(isCloud()){
									new Thread(new Runnable() {
										public void run() {
											try {
												NetUtil.deleteGroup(mContext, String.valueOf(adapter.getItem(position)), 1);
												handler.obtainMessage(DELETE_GROUP, position, 0, adapter).sendToTarget();
											} catch (Exception e) {
												handler.obtainMessage(ERROR, 0, 0, "删除分组失败").sendToTarget();
												e.printStackTrace();
											}
										}
									}).start();
								}else{
									new Thread(new Runnable() {
										public void run() {
											try {
												NetUtil.deleteGroup(mContext, String.valueOf(adapter.getItem(position)), 0);
												handler.obtainMessage(DELETE_GROUP, position, 0, adapter).sendToTarget();
											} catch (Exception e) {
												handler.obtainMessage(ERROR, 0, 0, "删除分组失败").sendToTarget();
												e.printStackTrace();
											}
										}
									}).start();
								}
								deleteDialog.cancel();

							}
						});
				((Button) dialogView.findViewById(R.id.btnCancel))
						.setOnClickListener(new OnClickListener() {

							public void onClick(View v) {
								deleteDialog.cancel();

							}
						});
			}
		});
		// 重命名分组
		btnReName.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				groupPopupWindow.dismiss();
				final View dialogView = mInflater.inflate(
						R.layout.dlg_add_group, null);
				final TextView messageText = (TextView) dialogView
						.findViewById(R.id.messageText);
				final EditText messageEdt = (EditText) dialogView
						.findViewById(R.id.messageEdit);
				messageEdt.setText((CharSequence) adapter.getItem(position));
				messageText.setText(getString(R.string.rename_group_msg));
				final Dialog renameDialog = new Dialog(mContext,
						R.style.DialogStyle);
				renameDialog.setContentView(dialogView);
				renameDialog.show();
				WindowManager.LayoutParams params = renameDialog.getWindow()
						.getAttributes();
				params.width = DLG_EDIT_GROUP_WIDTH;
				params.height = DLG_EDIT_GROUP_HEIGHT;
				renameDialog.getWindow().setAttributes(params);
				((Button) dialogView.findViewById(R.id.btnOk))
						.setOnClickListener(new OnClickListener() {

							public void onClick(View v) {
								final String newName = messageEdt.getText()
										.toString().trim();
								if (newName != null && !newName.equals("")) {
									for(int i = 0; i<adapter.getCount();i++){
										if(newName.equals(String.valueOf(adapter.getItem(i)))){
											Toast.makeText(mContext, "分组名称不能重复", Toast.LENGTH_SHORT).show();
											return;
										}
									}
									showProgressDialog(mContext, progressDialog, "正在重命名分组...");
									if(isCloud()){
										new Thread(new Runnable() {
											public void run() {
												try {
													NetUtil.editGroup(mContext,String.valueOf(adapter.getItem(position)), newName, 1);
													handler.obtainMessage(MODIFY_GROUP, position, 0, newName).sendToTarget();
												} catch (Exception e) {
													handler.obtainMessage(ERROR, 0, 0, "新增分组失败").sendToTarget();
													e.printStackTrace();
												}
											}
										}).start();
									}else {
										new Thread(new Runnable() {
											public void run() {
												try {
													NetUtil.editGroup(mContext, String.valueOf(adapter.getItem(position)), newName, 0);
													handler.obtainMessage(MODIFY_GROUP, position, 0, newName).sendToTarget();
												} catch (Exception e) {
													handler.obtainMessage(ERROR, 0, 0, "新增分组失败").sendToTarget();
													e.printStackTrace();
												}
											}
										}).start();
									}
									renameDialog.cancel();
								
								} else {
									Toast.makeText(mContext, "分组名称不能为空",
											Toast.LENGTH_LONG).show();
								}

							}
						});
				((Button) dialogView.findViewById(R.id.btnCancel))
						.setOnClickListener(new OnClickListener() {

							public void onClick(View v) {
								renameDialog.cancel();

							}
						});

			}
		});
	}

	/**
	 * 显示更多下拉弹出框
	 *@param currentView 当前屏幕 为1时为云好友，为2时为通讯好友
	 * */
	private void showPopupWindow(int currentView) {
		if (morePopupWindow != null) {
			// 通讯录好友标签下下拉按钮的视图
			LinearLayout commView = (LinearLayout) morePopupView
					.findViewById(R.id.commView);
			// 云好友标签下下拉按钮的视图
			LinearLayout couldView = (LinearLayout) morePopupView
					.findViewById(R.id.couldView);
			if (isCloud()) {
				if (!morePopupWindow.isShowing()) {
					morePopupWindow.showAsDropDown(btnMore, 0, 15);
					btnMore.setImageResource(R.drawable.more_fold);
					morePopupWindow
							.setOnDismissListener(new PopupWindow.OnDismissListener() {

								public void onDismiss() {
									btnMore.setImageResource(R.drawable.more_unfold);

								}
							});
				}

				Button btnFindFriends = (Button) morePopupView
						.findViewById(R.id.btnFindFriends);
				Button btnCloudManage = (Button) morePopupView
						.findViewById(R.id.btnCloudManage);
				commView.setVisibility(View.GONE);
				couldView.setVisibility(View.VISIBLE);
				if(currentCloudDelMode == IS_DELETE_MODE){//在删除模式下
					btnCloudManage.setText("退出管理模式");
				}else if(currentCloudDelMode == NOT_DELETE_MODE){//不在删除模式下
					btnCloudManage.setText("管理联系人");
				}
				btnFindFriends.setOnClickListener(this);
				btnCloudManage.setOnClickListener(this);

			} else {
				if (!morePopupWindow.isShowing()) {
					morePopupWindow.showAsDropDown(btnMore, 0, 15);
					btnMore.setImageResource(R.drawable.more_fold);
					morePopupWindow
							.setOnDismissListener(new PopupWindow.OnDismissListener() {

								public void onDismiss() {
									btnMore.setImageResource(R.drawable.more_unfold);

								}
							});
				}
				Button btnCreateNew = (Button) morePopupView
						.findViewById(R.id.btnCreateNew);
				Button btnImport = (Button) morePopupView
						.findViewById(R.id.btnImport);
				Button btnContactManage = (Button) morePopupView
						.findViewById(R.id.btnContactManage);
				if(currentCommDelMode == IS_DELETE_MODE){//在删除模式下
					btnContactManage.setText("退出管理模式");
				}else if(currentCommDelMode == NOT_DELETE_MODE){//不在删除模式下
					btnContactManage.setText("管理联系人");
				}
				couldView.setVisibility(View.GONE);
				commView.setVisibility(View.VISIBLE);
				btnCreateNew.setOnClickListener(this);
				btnImport.setOnClickListener(this);
				btnContactManage.setOnClickListener(this);
				if(contactList != null && contactList.size() != 0){
					btnContactManage.setEnabled(true);
				}else{
					btnContactManage.setEnabled(false);
				}
			}
		}
	}

	/**
	 * 显示载入提示对话框
	 * @param pDialog 传入对话框对象
	 * @param text 对话框显示内容
	 * */
	public void showProgressDialog(Context context, Dialog dialog, String text) {
//		dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//		dialog.setMessage(text);
		View view = LayoutInflater.from(context).inflate(R.layout.progress_dialog_view, null);
		dialog.setContentView(view);
		TextView message = (TextView) view.findViewById(R.id.message);
		message.setText(text);
		dialog.show();
		dialog.setOnDismissListener(new OnDismissListener() {

			public void onDismiss(DialogInterface dialog) {
				if (isCloud()) {
					if(loadCloudThread != null && loadCloudThread.isAlive()){
						loadCloudThread.interrupt();
					}
				} else {
					if(importThread != null && importThread.isAlive()){
						importThread.interrupt();
					}
					if(loadContactThread != null && loadContactThread.isAlive()){
						loadContactThread.interrupt();
					}
				}
			}
		});
	}

	/**
	 * 将联系人列表数据按照每屏固定数量分屏加入Viewpager的列表
	 * @param list 联系人列表数据
	 * */
	public ArrayList<View> setGrid(ArrayList<Contact> list) {
		ArrayList<View> viewList = new ArrayList<View>();
		int PageCount = (int) Math.ceil(list.size() / PAGE_SIZE);
		GridView singleScreen;
		for (int i = 0; i < PageCount; i++) {
			singleScreen = (GridView) LayoutInflater.from(this).inflate(
					R.layout.single_screen, null);
			LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, 
					LayoutParams.WRAP_CONTENT);
			singleScreen.setAdapter(new SingleScreenAdapter(mContext, list, i, 
					handler, currentView, progressDialog));
			singleScreen.setOnItemClickListener(gridListener);
			viewList.add(singleScreen);
		}
		return viewList;
	}
	
	/**
	 * 添加新联系人，若最后一屏不满，则在最后一屏添加，若已满则增加一屏
	 * @param contact 新建联系人对象
	 * @param viewPager 当前ViewPager对象
	 * @param context 句柄
	 * */
	public void addContact(ArrayList<Contact> list, Contact newContact, Context context){
		
//		ContactPageAdapter pageAdapter = (ContactPageAdapter)viewPager.getAdapter();
//		int count = pageAdapter.getCount();
//		SingleScreenAdapter adapter = (SingleScreenAdapter) ((GridView) pageAdapter.getItem(count - 1)).getAdapter();
//		int lastScreenCount = adapter.getCount();
//		if(lastScreenCount < PAGE_SIZE){
//			adapter.addItem(contact);
//		}else{
//			GridView child = (GridView) LayoutInflater.from(context).inflate(
//					R.layout.single_screen, null);
//			ArrayList<Contact> newArray = new ArrayList<Contact>();
//			SingleScreenAdapter newGridAdapter = new SingleScreenAdapter(context, newArray, pageAdapter.getCount(), 
//					handler, currentView, progressDialog);
//			child.setAdapter(newGridAdapter);
//			child.setOnItemClickListener(gridListener);
//			ContactPageAdapter newPageAdapter = (ContactPageAdapter)viewPager.getAdapter();
//			newPageAdapter.addItem(child);
//			newGridAdapter.addItem(contact);
//			viewPager.invalidate();
//		}
		char sortKey = PinYinUtil.getSortKey(newContact.displayName);
		int keyASC = sortKey;
		char nextKey = (char)(keyASC+1);
		if(Constant.DEBUG){
			Log.d(TAG, "displayName : "+newContact.displayName+" , sortKey : "+sortKey+" , nextKey : "+nextKey);
		}
		
		if(String.valueOf(sortKey).equals("#")){
			contactList.add(newContact);
			loadContactView(contactList);
			mViewPager.setCurrentItem(Math.round(contactList.size()/12), false);
		}else{
			int i = 0;
			for(Contact contact : list){
				if(String.valueOf(nextKey).equals(String.valueOf(contact.sortKey))){
					break;
				}
				i++;
			}
			contactList.add(i , newContact);
			loadContactView(contactList);
			mViewPager.setCurrentItem(Math.round(i/12), false);
		}
		
		
	}

	/**
	 * 管理联系人，显示删除按钮
	 * @param adapter 要管理的列表数组适配器
	 * */
	private void manageContact(ContactPageAdapter adapter){
		GridView everyScreen;
		if(isCloud()){
			if(currentCloudDelMode == IS_DELETE_MODE){//在删除模式下
				currentCloudDelMode = NOT_DELETE_MODE;
				int pageCount = adapter.getCount();
				for(int i = 0; i<pageCount; i++){
					everyScreen = (GridView) adapter.getItem(i);
					((SingleScreenAdapter) everyScreen.getAdapter()).exitManager();
				}
				morePopupWindow.dismiss();
			}else if(currentCloudDelMode == NOT_DELETE_MODE){//不在删除模式下
				currentCloudDelMode = IS_DELETE_MODE;
				int pageCount = adapter.getCount();
				for(int i = 0; i<pageCount ; i++){
					everyScreen = (GridView) adapter.getItem(i);
					((SingleScreenAdapter) everyScreen.getAdapter()).enterManager();
				}
				morePopupWindow.dismiss();
			}
		}else {
			if(currentCommDelMode == IS_DELETE_MODE){//在删除模式下
				currentCommDelMode = NOT_DELETE_MODE;
				int pageCount = adapter.getCount();
				for(int i = 0; i<pageCount; i++){
					everyScreen = (GridView) adapter.getItem(i);
					((SingleScreenAdapter) everyScreen.getAdapter()).exitManager();
				}
				morePopupWindow.dismiss();
			}else if(currentCommDelMode == NOT_DELETE_MODE){//不在删除模式下
				currentCommDelMode = IS_DELETE_MODE;
				int pageCount = adapter.getCount();
				for(int i = 0; i<pageCount ; i++){
					everyScreen = (GridView) adapter.getItem(i);
					((SingleScreenAdapter) everyScreen.getAdapter()).enterManager();
				}
				morePopupWindow.dismiss();
			}
		}
		
	}
	
	/**
	 * 判断当前画面是否在云好友界面上
	 * */
	private boolean isCloud(){
		if(currentView == 1){
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 设置当前显示列表
	 * @param list 将list设置为当前的显示列表
	 * */
	private void setCurrentList(ArrayList<Contact> list){
		currentList.clear();
		currentList.addAll(list);
	}
	
	/**
	 * 执行搜索
	 * */
	private void doSearch(){
		final String searchKey = searchEdit.getText().toString().trim();
		if (!searchKey.equals("")) {
//			showProgressDialog(mContext, progressDialog, "正在搜索...");
			if(isCloud()){
				new Thread(new Runnable() {
					public void run() {
						ArrayList<Contact> result = NetUtil.searchContacts(1, searchKey);
						handler.obtainMessage(SEARCH_FINISH, result).sendToTarget();
					}
				}).start();
			}else{
				new Thread(new Runnable() {
					public void run() {
						ArrayList<Contact> result = NetUtil.searchContacts(0, searchKey);
						handler.obtainMessage(SEARCH_FINISH, result).sendToTarget();
					}
				}).start();
			}
			
			
		} else {
			if(isCloud()){
				loadCloudView(cloudList);
			}else{
				loadContactView(contactList);
			}
		}
	}
	
	private void showImportDialog(){

		final View dialogView = mInflater.inflate(
				R.layout.dlg_add_group, null);
		final EditText messageEdit = ((EditText) dialogView
				.findViewById(R.id.messageEdit));
		final TextView messageText = ((TextView) dialogView
				.findViewById(R.id.messageText));
		final TextView titleText = ((TextView) dialogView
				.findViewById(R.id.titleText));
		messageEdit.setVisibility(View.GONE);
		messageText.setText("从本地通讯录联系人中导入联系人数据");
		titleText.setText(getString(R.string.delete_group_title));
		final Dialog deleteDialog = new Dialog(mContext,
				R.style.DialogStyle);
		deleteDialog.setContentView(dialogView);
		deleteDialog.show();
		WindowManager.LayoutParams params = deleteDialog.getWindow()
				.getAttributes();
		params.width = LayoutParams.WRAP_CONTENT;
		params.height = LayoutParams.WRAP_CONTENT;
		deleteDialog.getWindow().setAttributes(params);
		((Button) dialogView.findViewById(R.id.btnOk))
				.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						showProgressDialog(mContext, progressDialog,"正在导入本地通讯录并同步到服务器，请稍候");
						importThread = new Thread(new Runnable() {
							
							public void run() {
								try {
									ArrayList<Contact> result = NetUtil.importSystemContacts(mContext);
									if(ContactsUtils.validateIsNotNull(result)){
										contactList.addAll(result);
										MainActivity.contactFriends.addAll(contactList);
										handler.sendEmptyMessage(IMPORT_CONTACT_FINISH);
									}else{
										handler.obtainMessage(ERROR, 0, 0, "本地通讯录暂无联系人").sendToTarget();
									}
								} catch (Exception e) {
									e.printStackTrace();
									handler.obtainMessage(ERROR, 0, 0, e.toString()).sendToTarget();
								}
							}
						});
						importThread.start();
						deleteDialog.cancel();

					}
				});
		((Button) dialogView.findViewById(R.id.btnCancel))
				.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						deleteDialog.cancel();

					}
				});
	
	}
}
